package org.jeecg.modules.demo.workflow.instanceState;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.modules.demo.utils.R;
import org.jeecg.modules.demo.workflow.service.ProcessTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.flowable.engine.TaskService;
import org.flowable.engine.task.Comment;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.entity.ZyHazardInvestigation;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.entity.ZyRectificationInformation;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.entity.ZyReviewInformation;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.service.IZyHazardInvestigationService;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.service.IZyRectificationInformationService;
import org.jeecg.modules.demo.safemanage.zyhazardinvestigation.service.IZyReviewInformationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 功能描述
 *
 * @program: jeecg-boot
 * @description:
 * @author: wwq
 * @create: 2024-04-21 16:31
 **/
@Api(tags="中阳隐患排查流程状态")
@RestController
@RequestMapping("wflow/ZyHazardInvestigationState")
public class ZyHazardInvestigationState {
    @Autowired
    private IZyHazardInvestigationService zyHazardInvestigationService;
    @Autowired
    private ProcessTaskService taskService;
    @Autowired
    private TaskService taskServiceFlowable;
    @Autowired
    private IZyRectificationInformationService zyRectificationInformationService;
    @Autowired
    private IZyReviewInformationService zyReviewInformationService;

    private ExecutorService executor = Executors.newFixedThreadPool(5); // 创建一个固定大小为5的线程池

    /**
     * 流程通过时监听器调用接口
     * -通过状态
     * @param
     */
    @AutoLog(value = "中阳环境建筑垃圾-通过状态")
    @ApiOperation(value = "中阳环境建筑垃圾-通过状态", notes = "中阳环境建筑垃圾-通过状态")
    @PostMapping("setPassState11")
    public Object setPassStatus11() {
        System.out.println("11111111111");
        return R.ok("ok");

    }
    /**
     * 流程通过时监听器调用接口
     * 隐患排查-通过状态
     * @param instanceId 流程实例ID
     */
    @AutoLog(value = "隐患排查-通过状态")
    @ApiOperation(value = "隐患排查-通过状态", notes = "隐患排查-通过状态")
    @PostMapping("setPassState")
    public Object setPassStatus(@RequestParam String instanceId) {
        System.out.println("instanceId = " + instanceId);
        String  mainDesc = "流程进行中";
        String rectifierDesc = "未整改";
        String reviewerDesc = "未复查";
        String result = "待整改";

        String s = "";
        String personName = "";
        String parentId = "";
        Map<String, Object> task = taskService.getTaskById(instanceId);
        System.out.println("task = " + task);
        // 使用线程池执行异步任务
        String finalParentId = parentId;
        executor.execute(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            List<Comment> processInstanceComments = taskServiceFlowable.getProcessInstanceComments(instanceId);
            String actComment = "";
            Date time = null;
            String text = "";
            String concatenatedUrls = null;
            System.out.println("processInstanceComments = " + processInstanceComments);
            if (!processInstanceComments.isEmpty()){
                for (Comment comment : processInstanceComments) {
                    System.out.println("acr1: " + comment.toString());
                    String id = (String) task.get("id");
                    if (id.equals(comment.getTaskId())) {
                        actComment = comment.getFullMessage();
                        time = comment.getTime();
                    }
                }

                System.out.println("act:" + actComment);
                // 解析 JSON 字符串
                JSONObject jsonObject = JSON.parseObject(actComment);

                // 获取 attachments 数组
                JSONArray attachments = jsonObject.getJSONArray("attachments");

                List<String> urlList = new ArrayList<>();
                // 提取两个 url
                for (int i = 0; i < attachments.size(); i++) {
                    JSONObject attachment = attachments.getJSONObject(i);
                    String url = attachment.getString("url");
                    System.out.println("URL " + (i + 1) + ": " + url);
                    urlList.add(url);
                }
                concatenatedUrls = String.join(",", urlList);
                System.out.println("Concatenated URLs: " + concatenatedUrls);

                // 获取 text 内容
                text = jsonObject.getString("text");
                System.out.println("Text: " + text);

            }else {
                text = "流程被拒绝";
                time= new Date();
            }
            String realname = (String) task.get("realname");
            String name1 = (String) task.get("name");




            ZyHazardInvestigation zyHazardInvestigation = zyHazardInvestigationService.getOne(new LambdaQueryWrapper<ZyHazardInvestigation>().
                    eq(ZyHazardInvestigation::getInstanceId, instanceId));
            if ("整改人".equals(name1)){
                System.out.println("finalParentId = " + zyHazardInvestigation.getId());
                zyRectificationInformationService.save(ZyRectificationInformation.builder().rectificationPersonnel(realname).completionTime(time)
                        .rectificationInfo(text).rectificationPhoto(concatenatedUrls).status("已整改").parentId(zyHazardInvestigation.getId()).build());
            }
            if ("复查人".equals(name1)) {
                System.out.println("finalParentId = " + zyHazardInvestigation.getId());
                zyReviewInformationService.save(ZyReviewInformation.builder().reviewPersonnel(realname).reviewTime(time)
                        .reviewDesc(text).reviewPhoto(concatenatedUrls).status("已复查").parentId(zyHazardInvestigation.getId()).build());
            }
        });

        if (task != null) {
            s = (String) task.get("taskDefinitionKey");
            System.out.println("s = " + s);
            personName = (String) task.get("name");
            if ("整改人".equals(personName)){
                rectifierDesc = "已整改";
                result = "待复查";
            }
            if ("复查人".equals(personName)) {
                mainDesc = "流程通过";
                rectifierDesc = "已整改";
                reviewerDesc = "已复查";
                result = "合格";
            }
            System.out.println("personName = " + personName);
        }

        ZyHazardInvestigation zyHazardInvestigation = zyHazardInvestigationService.getOne(new LambdaQueryWrapper<ZyHazardInvestigation>().
                eq(ZyHazardInvestigation::getInstanceId, instanceId));
        zyHazardInvestigation.setStatus(mainDesc);
        zyHazardInvestigation.setRectifierStatus(rectifierDesc);
        zyHazardInvestigation.setReviewerStatus(reviewerDesc);
        zyHazardInvestigation.setResult(result);
        zyHazardInvestigationService.updateById(zyHazardInvestigation);

        return R.ok(mainDesc);
    }



    /**
     * 流程通过时监听器调用接口
     * 隐患排查-驳回状态
     * @param instanceId 流程实例ID
     */
    @AutoLog(value = "隐患排查-驳回状态")
    @ApiOperation(value = "隐患排查-驳回状态", notes = "隐患排查-驳回状态")
    @PostMapping("setRefuseState")
    public Object setRefuseStatus(@RequestParam String instanceId) {
        System.out.println("instanceId = " + instanceId);
        String  mainDesc = "审批被驳回";
        String rectifierDesc = "未整改";
        String reviewerDesc = "未复查";
        String result = "不合格";

        String s = "";
        String personName = "";
        String parentId = "";
        Map<String, Object> task = taskService.getTaskById(instanceId);
        System.out.println("task = " + task);
        // 使用线程池执行异步任务
        String finalParentId = parentId;
        executor.execute(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }


            List<Comment> processInstanceComments = taskServiceFlowable.getProcessInstanceComments(instanceId);
            String actComment = "";
            Date time = null;
            String text = "";
            String concatenatedUrls = null;
            System.out.println("processInstanceComments = " + processInstanceComments);
            if (!processInstanceComments.isEmpty()){
                for (Comment comment : processInstanceComments) {
                    System.out.println("acr1: " + comment.toString());
                    String id = (String) task.get("id");
                    if (id.equals(comment.getTaskId())) {
                        actComment = comment.getFullMessage();
                        time = comment.getTime();
                    }
                }

                System.out.println("act:" + actComment);
                // 解析 JSON 字符串
                JSONObject jsonObject = JSON.parseObject(actComment);

                // 获取 attachments 数组
                JSONArray attachments = jsonObject.getJSONArray("attachments");

                List<String> urlList = new ArrayList<>();
                // 提取两个 url
                for (int i = 0; i < attachments.size(); i++) {
                    JSONObject attachment = attachments.getJSONObject(i);
                    String url = attachment.getString("url");
                    System.out.println("URL " + (i + 1) + ": " + url);
                    urlList.add(url);
                }
                concatenatedUrls = String.join(",", urlList);
                System.out.println("Concatenated URLs: " + concatenatedUrls);

                // 获取 text 内容
                text = jsonObject.getString("text");
                System.out.println("Text: " + text);

            }else {
                text = "流程被拒绝";
                time= new Date();
            }
            String realname = (String) task.get("realname");
            String name1 = (String) task.get("name");


            ZyHazardInvestigation zyHazardInvestigation = zyHazardInvestigationService.getOne(new LambdaQueryWrapper<ZyHazardInvestigation>().
                    eq(ZyHazardInvestigation::getInstanceId, instanceId));
            if ("整改人".equals(name1)){
                System.out.println("finalParentId = " + zyHazardInvestigation.getId());
                zyRectificationInformationService.save(ZyRectificationInformation.builder().rectificationPersonnel(realname).completionTime(time)
                        .rectificationInfo(text).rectificationPhoto(concatenatedUrls).status("已整改").parentId(zyHazardInvestigation.getId()).build());
            }
            if ("复查人".equals(name1)) {
                System.out.println("finalParentId = " + zyHazardInvestigation.getId());
                zyReviewInformationService.save(ZyReviewInformation.builder().reviewPersonnel(realname).reviewTime(time)
                        .reviewDesc(text).reviewPhoto(concatenatedUrls).status("已复查").parentId(zyHazardInvestigation.getId()).build());
            }
        });

        if (task != null) {
            s = (String) task.get("taskDefinitionKey");
            System.out.println("s = " + s);
            personName = (String) task.get("name");
            if ("整改人".equals(personName)){
                rectifierDesc = "整改驳回";
                result = "不合格";
            }
            if ("复查人".equals(personName)) {
                reviewerDesc = "复查驳回";
                result = "不合格";
            }
            System.out.println("personName = " + personName);
        }

        ZyHazardInvestigation zyHazardInvestigation = zyHazardInvestigationService.getOne(new LambdaQueryWrapper<ZyHazardInvestigation>().
                eq(ZyHazardInvestigation::getInstanceId, instanceId));
        zyHazardInvestigation.setStatus(mainDesc);
        zyHazardInvestigation.setRectifierStatus(rectifierDesc);
        zyHazardInvestigation.setReviewerStatus(reviewerDesc);
        zyHazardInvestigation.setResult(result);
        zyHazardInvestigationService.updateById(zyHazardInvestigation);
        return R.ok(mainDesc);

    }

    /**
     * 流程通过时监听器调用接口
     * 隐患排查-撤销状态
     * @param instanceId 流程实例ID
     */
    @AutoLog(value = "隐患排查-撤销状态")
    @ApiOperation(value = "隐患排查-撤销状态", notes = "隐患排查-撤销状态")
    @PostMapping("setCancelState")
    public Object setCancelStatus(@RequestParam String instanceId) {
        System.out.println("instanceId = " + instanceId);
        String  mainDesc = "审批被撤销";
        String rectifierDesc = "未整改";
        String reviewerDesc = "未复查";
        String result = "不合格";

        String s = "";
        String personName = "";
        String parentId = "";
        Map<String, Object> task = taskService.getTaskById(instanceId);
        System.out.println("task = " + task);
        // 使用线程池执行异步任务
        String finalParentId = parentId;
        executor.execute(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }


            List<Comment> processInstanceComments = taskServiceFlowable.getProcessInstanceComments(instanceId);
            String actComment = "";
            Date time = null;
            String text = "";
            String concatenatedUrls = null;
            System.out.println("processInstanceComments = " + processInstanceComments);
            if (!processInstanceComments.isEmpty()){
                for (Comment comment : processInstanceComments) {
                    System.out.println("acr1: " + comment.toString());
                    String id = (String) task.get("id");
                    if (id.equals(comment.getTaskId())) {
                        actComment = comment.getFullMessage();
                        time = comment.getTime();
                    }
                }

                System.out.println("act:" + actComment);
                // 解析 JSON 字符串
                JSONObject jsonObject = JSON.parseObject(actComment);

                // 获取 attachments 数组
                JSONArray attachments = jsonObject.getJSONArray("attachments");

                List<String> urlList = new ArrayList<>();
                // 提取两个 url
                for (int i = 0; i < attachments.size(); i++) {
                    JSONObject attachment = attachments.getJSONObject(i);
                    String url = attachment.getString("url");
                    System.out.println("URL " + (i + 1) + ": " + url);
                    urlList.add(url);
                }
                concatenatedUrls = String.join(",", urlList);
                System.out.println("Concatenated URLs: " + concatenatedUrls);

                // 获取 text 内容
                text = jsonObject.getString("text");
                System.out.println("Text: " + text);

            }else {
                text = "流程被撤销";
                time= new Date();
            }
            String realname = (String) task.get("realname");
            String name1 = (String) task.get("name");


            ZyHazardInvestigation zyHazardInvestigation = zyHazardInvestigationService.getOne(new LambdaQueryWrapper<ZyHazardInvestigation>().
                    eq(ZyHazardInvestigation::getInstanceId, instanceId));
            if ("整改人".equals(name1)){
                System.out.println("finalParentId = " + zyHazardInvestigation.getId());
                zyRectificationInformationService.save(ZyRectificationInformation.builder().rectificationPersonnel(realname).completionTime(time)
                        .rectificationInfo(text).rectificationPhoto(concatenatedUrls).status("已整改").parentId(zyHazardInvestigation.getId()).build());
            }
            if ("复查人".equals(name1)) {
                System.out.println("finalParentId = " + zyHazardInvestigation.getId());
                zyReviewInformationService.save(ZyReviewInformation.builder().reviewPersonnel(realname).reviewTime(time)
                        .reviewDesc(text).reviewPhoto(concatenatedUrls).status("已复查").parentId(zyHazardInvestigation.getId()).build());
            }
        });

        if (task != null) {
            s = (String) task.get("taskDefinitionKey");
            System.out.println("s = " + s);
            personName = (String) task.get("name");
            if ("整改人".equals(personName)){
                rectifierDesc = "整改撤销";
                result = "不合格";
            }
            if ("复查人".equals(personName)) {
                reviewerDesc = "复查撤销";
                result = "不合格";
            }
            System.out.println("personName = " + personName);
        }

        ZyHazardInvestigation zyHazardInvestigation = zyHazardInvestigationService.getOne(new LambdaQueryWrapper<ZyHazardInvestigation>().
                eq(ZyHazardInvestigation::getInstanceId, instanceId));
        zyHazardInvestigation.setStatus(mainDesc);
        zyHazardInvestigation.setRectifierStatus(rectifierDesc);
        zyHazardInvestigation.setReviewerStatus(reviewerDesc);
        zyHazardInvestigation.setResult(result);
        zyHazardInvestigationService.updateById(zyHazardInvestigation);
        return R.ok(mainDesc);

    }


}
